package com.cal.utms.util;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.Locale;

import com.cal.utms.dto.maintenance.HolidayCalendarDto;
import com.cal.utms.model.maintenance.HolidayModel;

public class NextDate {

	HolidayModel holidayModel = new HolidayModel();
	SimpleDateFormat format = new SimpleDateFormat("dd/MM/yyyy", Locale.ENGLISH);

	public Date getNextDate(Date monIntStartDate, String type) {

		String dt = format.format(monIntStartDate);
		Calendar c = Calendar.getInstance();
		try {
			c.setTime(format.parse(dt));
			if (type.equals("M"))
				c.add(Calendar.MONTH, 1);
			else if (type.equals("Q"))
				c.add(Calendar.MONTH, 3);
			else if (type.equals("S"))
				c.add(Calendar.MONTH, 6);
			else if (type.equals("A"))
				c.add(Calendar.MONTH, 12);
			dt = format.format(c.getTime());
			return checkHolidays(dt);
		} catch (ParseException e) {
			e.printStackTrace();
			return null;
		}
	}

	@SuppressWarnings("static-access")
	private Date checkHolidays(String parse) {

		Date nextDate = null;
		String dt = parse;
		Calendar c = Calendar.getInstance();
		try {
			c.setTime(format.parse(dt));
			dt = format.format(c.getTime());
			int year = c.get(c.YEAR);
			int month = c.get(c.MONTH);
			int dayOfWeek = c.get(c.DAY_OF_WEEK);
			if (dayOfWeek != 1 && dayOfWeek != 7) {
				List<HolidayCalendarDto> calendarDtos = holidayModel.getHolidaysByMonthYear(year, month + 1);
				if (calendarDtos.size() > 0) {
					for (HolidayCalendarDto holidayCalendarDto : calendarDtos) {
						if (holidayCalendarDto.getDate().equals(dt)) {
							c.add(Calendar.DATE, 1);
							dt = format.format(c.getTime());
							nextDate = checkHolidays(dt);
							break;
						} else {
							nextDate = format.parse(dt);
							break;
						}
					}
				} else {
					nextDate = format.parse(dt);
				}
			} else {
				c.add(Calendar.DATE, 1);
				dt = format.format(c.getTime());
				nextDate = checkHolidays(dt);
			}
		} catch (ParseException e) {
			e.printStackTrace();
		}

		return nextDate;
	}

}
